package com.xb.loan.cashier.alipay.util;

import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CSVUtils {

    private static String charset = "gbk";

    private static void writeRow(List<String> row, BufferedWriter csvWriter, boolean isLastLine) throws IOException {
        for (String data : row) {
            StringBuffer sb = new StringBuffer();
        //    String rowStr = sb.append("\"").append(data).append("\",").toString();
            String rowStr = sb.append(data.trim()).append(",").toString();
            csvWriter.write(rowStr);
        }
        if(!isLastLine)
            csvWriter.newLine();  
    }

    public static void createCSVFile(String filePath, List<List<String>> data) {

        File csvFile = null;
        BufferedWriter csvWtriter = null;
        try {
            csvFile = new File(filePath);
            File parent = csvFile.getParentFile();
            if (parent != null && !parent.exists()) {
                parent.mkdirs();
            }
            csvFile.createNewFile();

            csvWtriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(csvFile), charset), 1024);
            // 写入文件内容
           /* for (List<String> row : data) {
                writeRow(row, csvWtriter,);
            }*/
            
            for(int i=0;i<data.size();i++)
            {
                writeRow(data.get(i),csvWtriter,(data.size()-1==i));   
            }
            csvWtriter.flush();
            
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                csvWtriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /** 
    * 下载文件 
    * @param response 
    * @param csvFilePath 
    *              文件路径 
    * @param fileName 
    *              文件名称 
    * @throws IOException
    */
    public static void exportFile(HttpServletResponse response, String csvFilePath, String fileName) throws IOException {
        response.setContentType("application/csv;charset=GBK");
        response.setHeader("Content-Disposition", "attachment;  filename=" + new String(fileName.getBytes("GBK"), "ISO8859-1"));
        //URLEncoder.encode(fileName, "GBK")  

        InputStream in = null;
        try {
            in = new FileInputStream(csvFilePath);
            int len = 0;
            byte[] buffer = new byte[1024];
            response.setCharacterEncoding("GBK");
            OutputStream out = response.getOutputStream();
            while ((len = in.read(buffer)) > 0) {
                //out.write(new byte[] { (byte) 0xEF, (byte) 0xBB, (byte) 0xBF });  
                out.write(buffer, 0, len);
            }
        } catch (FileNotFoundException e) {
            System.out.println(e);
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

    /** 
    * 删除该目录filePath下的所有文件 
    * @param filePath 
    *            文件目录路径 
    */
    public static void deleteFiles(String filePath) {
        File file = new File(filePath);
        if (file.exists()) {
            File[] files = file.listFiles();
            for (int i = 0; i < files.length; i++) {
                if (files[i].isFile()) {
                    files[i].delete();
                }
            }
        }
    }

    /** 
    * 删除单个文件 
    * @param filePath 
    *         文件目录路径 
    * @param fileName 
    *         文件名称 
    */
    public static void deleteFile(String filePath, String fileName) {
        File file = new File(filePath);
        if (file.exists()) {
            File[] files = file.listFiles();
            for (int i = 0; i < files.length; i++) {
                if (files[i].isFile()) {
                    if (files[i].getName().equals(fileName)) {
                        files[i].delete();
                        return;
                    }
                }
            }
        }
    }

    public static List<List<String>> readCSVFile(String file) throws IOException {
        InputStreamReader fr = new InputStreamReader(new FileInputStream(file), "gbk");
        BufferedReader br = new BufferedReader(fr);
        String rec = null;// 一行
        String str;// 一个单元格
        List<List<String>> listFile = new ArrayList<List<String>>();
        try {
            // 读取一行  
            while ((rec = br.readLine()) != null) {  
                int index=0;  
                Pattern pCells = Pattern
                        .compile("(\"[^\"]*(\"{2})*[^\"]*\")*[^,]*,");  
                Matcher mCells = pCells.matcher(rec);
                List<String> cells = new ArrayList<String>();// 每行记录一个list
                // 读取每个单元格  
                while (mCells.find()) {  
                    str = mCells.group();  
                    str = str.replaceAll(  
                            "(?sm)\"?([^\"]*(\"{2})*[^\"]*)\"?.*,", "$1");  
                    str = str.replaceAll("(?sm)(\"(\"))", "$2");  
                    cells.add(str);  
                    index = mCells.end();  
                }  
                cells.add(rec.substring(index));  
                listFile.add(cells);  
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fr != null) {
                fr.close();
            }
            if (br != null) {
                br.close();
            }
        }
        return listFile;
    }

    public static void main(String[] args) throws IOException {
        String file = "D:\\encash\\encash\\100_1_1601191606000005.csv";
    //   String file="d:/temp/ALIPAY__RESULT.csv";
     //  String file="d:/temp/100_1_1509072000040001.csv";
      //  String file2 = "d:/temp/444.csv";
        /*List<List<String>> list = readCSVFile(file);
        Map<String,Double> map = new HashMap<String,Double>();
        List<List<String>> list1 =  EnCashValueBean.getAlipayEncashDetail(list,map);
        List<List<String>> listNew = EnCashValueBean.getRefundList(list1);
        createCSVFile("d:/temp/new.csv", listNew);*/
        BufferedReader reader = null;
        String line = null;
        int row = 1;
        reader = new BufferedReader(new InputStreamReader(new FileInputStream("d:/temp/new.csv"), "GBK"));
        while(true){
        	line = reader.readLine();
            if(row++<4){
                continue;
            }
            if(StringUtils.isBlank(line)){
                break;
            }
            String[] values = line.split(",");
            String orderId = values[1];//  流水号
            System.out.println(orderId);
        }
       /* for (List<String> temp : list) {
            for (String str : temp) {
                System.out.print(str);
                System.out.print("     ");
            }
            System.out.println("");
        }
        String file3 = "d:/temp/444.csv";
        String file4 = "d:/temp/555.csv";
        Map<String,Double> map = new HashMap<String,Double>();
        List list1 =  EnCashValueBean.getAlipayEncashDetail(list,map);
        List list2 = EnCashValueBean.getAlipayEncashCollect("112345",list,map);
        createCSVFile(file3, list2);
        createCSVFile(file4,  list1);*/
    }
}